/* api */
import{ createBatchPlanTask, getTaskAllotList, getTaskAllotListInitData, getCurrentAllTaskTypeList } from '@src/api/TaskApi'
import { getAsyncTaskViewInitData } from '@src/api/InitDataApi'
/* components */
import BizListViewTask from '@src/component/business/BizListView/Impl/BizListViewTask/BizListViewTask'
/* computed */
import TaskAllotListComputed from '@src/modules/task/taskTypes/allot/TaskAllotListComputed'
/* enum */
import ComponentNameEnum from '@model/enum/ComponentNameEnum'
import Field from '@model/entity/Field'
/* model */
import { getColumnFields, getAdvancedFields } from '@src/modules/task/taskTypes/allot/fields'
import { getTaskAllotInitDataResult } from '@model/param/out/Task'
import { commonUseItemType } from '@src/component/AdvancedSearch/advancedSearch'
/* utils */
import Log from '@src/util/log'
import { debounce } from '@src/util/function'
import Platform from '@src/util/platform'
import StorageUtil from '@src/util/storage.ts';
import StorageModuleEnum from '@model/enum/StorageModuleEnum';
import { allotTaskJump } from '@service/TaskService'
import { useFormTimezone } from 'pub-bbx-utils'
const { disposeFormItemViewTime } = useFormTimezone()

class TaskAllotListMethods extends TaskAllotListComputed {
  public computedListPxArray(){
    let padding = [24, 16, 6];
    return padding;
  }
  public changePackUpLocal(){
    this.changePackUp()
  }
  public toggleMapShow(show: boolean = true) {
    this.mapShow = show
    // 地图模式时默认收起
    show && this.packUp ? this.changePackUp() : ''
  }
  /**
   * @description 构建高级搜索列
   */
  public buildAdvancedColumns() {
    this.advanceSearchColumns = this.advancedSearchColumnsFilterHandler([
      ...this.getAdvancedFields(this)
    ])
  }
  
  /**
   * @description: 获取高级搜索字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 高级搜索字段列表
   */  
  public getAdvancedFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、曾打印字段
    let advancedFields = getAdvancedFields(vm).filter(field => field.show)
    if (this.isBasicEditionHideProduct) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      advancedFields = advancedFields.filter(field => field.fieldName !== 'oncePrinted')
    }

    return advancedFields
  }
  
  /**
   * @description: 获取表格列字段列表
   * @param {BizListViewTask} vm 当前实例
   * @return {Field[]} 表格列字段列表
   */  
  public getColumnFields(vm: BizListViewTask): Field[] {
    // 基础版过滤产品、曾打印字段
    let columnFields = getColumnFields(vm);
    if (this.isBasicEditionHideProduct) {
      columnFields = columnFields.filter(field => field.fieldName !== 'product')
    }
    if (this.isBasicEditionHidePrintTask) {
      columnFields = columnFields.filter(field => field.fieldName !== 'oncePrinted')
    }
    console.log(columnFields, 'columnFieldscolumnFieldscolumnFields')
    return columnFields
  }
  
  /** 
   * @description 获取属性
  */
  public getAttributes() {
    const classNames: string[] = [ComponentNameEnum.TaskAllotList, 'common-list-container__v2']
    
    return {
      class: classNames,
      directives: [
        // {
        //   name: 'loading',
        //   value: this.loading
        // }
      ]
    }
  }
  
  /**
   * @description 获取按钮的类型
   * @param {boolean} isSelected 是否选中
   * @return {String} 按钮类型
   */  
  public getButtonType(isSelected: boolean): string {
    return isSelected ? 'primary' : 'ghost'
  }
  
  public fetchTableListData() {
    const params = {
      ...this.searchParams,
      ...this.advancedSearchModel,
    }
    // 地图模式时触发地图模式搜索
    this.$nextTick(() => {
      if (this.mapShow && this.$refs.AllotMapDialogComponent) {
        this.$refs.AllotMapDialogComponent.init()
      }
    })
    this.fetchTaskList(params, getTaskAllotList)
  }
  
  /**
   * @description: 获取初始化数据
   * @return {Promise<void>}
   */  
  public async fetchInitData(): Promise<void> {
    this.loading = true
    
    return (
      getTaskAllotListInitData()
        .then(async (result: getTaskAllotInitDataResult) => {
          this.initData = result
          this.taskTypes = result?.taskTypeList || []
          this.taskConfig = result?.taskConfig || null
          this.auth = result?.authorities || {}
        })
        .catch(error => {
          Log.error(error, this.fetchInitData.name)
        })
    )
  }
  
  /**
   * @description: 初始化工单类型所有字段
   * 工单类型变化之后的事件
   * 1. 获取工单类型字段
   * 2. 构建高级搜索列
   * @return {void}
   */  
  public async initializeTaskTypeAllFields(): Promise<void> {
    // 获取工单类型字段
    await this.fetchTaskFields()
    // 构建高级搜索列
    this.buildAdvancedColumns()
  }
  
  /**
   * @description 提交计划任务
   * @param {Record} planTaskParams 计划任务参数
   * @return {void}
   */  
  public submitWithPlanTask(planTaskParams: Record<string, any>): void {
    debounce(async () => {
      const params = { ids: this.selectedIds, planTask: planTaskParams }
      
      try {
        // 切换计划任务组件等待状态
        this.togglePlanTaskEditFormComponentPending()
        // 批量新建计划任务
        const result = await createBatchPlanTask(params)
        // 提示
        Platform.alert(result?.message)
        
        // 成功则刷新页面
        if (result.succ) {
          window.location.reload()
        }
        
      } catch (error) {
        Log.error(error, this.submitWithPlanTask.name)
      } finally {
        this.togglePlanTaskEditFormComponentPending(false)
      }
    })
  }
  
  /**
   * @description 显示计划任务弹窗
   * @return {void}
   */  
  public showPlanTaskDialog(): void {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('PLAN_TASK_BTN'));

    const validated = this.selectedTaskDataValidate()
    if (!validated) return
    
    // @ts-ignore
    this.PlanTaskEditFormComponent?.toggle()
  }
  
  /**
   * @description 显示地图派单弹窗
   * @return {void}
   */  
  public showMapAllotDialog(): void {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('ALLOT_MAP_BTN'));
    this.toggleMapShow(true)
    this.AllotMapDialogComponent?.init()
  }
  
  /**
   * @description 显示批量指派弹窗
   * @return {void}
   */  
  public showBatchAllotDialog(): void {
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('BATCH_ALLOT_BTN'));
    const validated = this.selectedTaskDataValidate()
    if (!validated) return
    
    // @ts-ignore
    this.BatchAllotDialogComponent?.openDialog(this.taskConfig)
  }
  
  public togglePlanTaskEditFormComponentPending(pending: boolean = true) {
    // @ts-ignore
    this.PlanTaskEditFormComponent?.togglePending(pending)
  }
  
  public refresh() {
    this.loading = true
    setTimeout(async () => {
      this.BizTableComponent?.outsideClearSelection()
      this.multipleSelection = []
      await this.search()
      // this.loading = false
    }, 1000)
  }

  public changeTaskType(item:any){
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('QUICK_SEARCH', '工单类型'));

    const { name, id } = item
    this.currentTaskType = {
      id,
      name,
      templateId: id
    }
    this.initializeTaskTypeAllFields()
    this.refresh()
  }

  /**
   * 高级搜索
   * @param searchModel
   */
  public handleAdvancedSearch(searchModel: any = {}){
    this.advancedSearchModel = searchModel;
    this.search();
  }

  /**
   * 常用字段切换
   * @param {*} fieldName
   * @param {*} isChecked
   */
  public changeCommonUse({fieldName, isChecked}: commonUseItemType){
    const inCommonUseSet = new Set(this.inCommonUse)
    if(isChecked){
      inCommonUseSet.add(fieldName)
    }else {
      inCommonUseSet.delete(fieldName);
    }
    this.inCommonUse = Array.from(inCommonUseSet);
    try {
      StorageUtil.storageSet(this.advancedSearchFieldStorageKey, this.inCommonUse, StorageModuleEnum.Task)
    } catch (error) {
      console.error('changeCommonUse ~ setIndexedDbData ~ error', error)
    }
  }

  /**
   * 恢复常用字段
   */
  public async recoverCommonUse(){
    try {
      this.inCommonUse = await StorageUtil.storageGet(this.advancedSearchFieldStorageKey, [], StorageModuleEnum.Task)
    } catch (error) {
      console.error('获取常用字段 recoverCommonUse', error);
      return Promise.reject(error)
    }
  }

  /**
   * 指派
   */
  public allotTask(task: any) {
    this.$set(task, 'allotLoading', true)
    // @ts-ignore
    this.$track.clickStat(this.$track.formatParams('TASK_ALLOT'));
    // 目前指派工单列表和工单详情的数据字段对不上，所以暂时先通过init返回的数据去唤起指派弹框，更稳妥些~
    getAsyncTaskViewInitData({
      allot: true, // 这个不知道有没有用，不过详情有带上
      id: task.id
    }).then(async result => {
      const initData = result?.data?.initJson || {}
      // 按照工单详情的逻辑~
      if(initData?.restructAllot !== true) {
        allotTaskJump(task, true)
        return
      }
      // 按照工单详情initData的处理~
      if (initData.task?.state && initData.task?.isDelete == 5) {
        initData.task.state = 'draft'
      }
      this.currOperationTask = initData.task || {}
      this.currLoginUser = initData.loginUser || {}
      // 按照工单详情时间数据的处理~
      const { planStartTime, planEndTime } = this.currOperationTask;
      if(planStartTime) {
        this.currOperationTask.planStartTime = disposeFormItemViewTime(this.planStartTimeField || {}, planStartTime)
      }
      if(planEndTime) {
        this.currOperationTask.planEndTime = disposeFormItemViewTime(this.planStartTimeField || {}, planEndTime)
      }
      // @ts-ignore
      await this.TaskAllotModalComponent?.outsideShow()
      setTimeout(() => {
        this.$set(task, 'allotLoading', false)
      }, 3000)
    })
  }
  /**
   * 指派成功
   */
  public allotSuccess() {
    // @ts-ignore
    this.TaskAllotModalComponent?.close()
    this.refresh()
  }
}

export default TaskAllotListMethods
